<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="about">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <a-input-search
            v-model:value="searchKeyword"
            placeholder="请搜索"
            enter-button="搜索"
            @search="handleSearch"
        />
        <a-button type="primary" @click="showModal1">
          新增
        </a-button>
      </a-space>
      <a-table :columns="columns" :row-key="item => item.companyId" :data-source="companies" :pagination="pagination"
               :loading="isLoading" @change="handleTableChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'logoUrl'">
            <img :src="record.logoUrl" alt="Logo" style="width: 50px; height: 50px; border-radius: 50%;"/>
            <div v-if="!record.logoUrl">Logo链接为空</div>
          </template>
          <template v-if="column.dataIndex === 'isVerified'">
            <span>{{ record.isVerified ? '已认证' : '未认证' }}</span>
          </template>
          <template v-if="column.dataIndex === 'createdAt'">
            <span>{{ formatDate(record.createdAt) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="showModal(record)">
                编辑
              </a-button>
              <a-popconfirm
                  title="是否确认要删除?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteCompany(record)"
              >
                <a-button danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>
  <!-- 模态框 更新-->
  <a-modal v-model:open="open" title="编辑公司" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form :model="selectedCompany" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="公司名称">
        <a-input v-model:value="selectedCompany.companyName" />
      </a-form-item>
      <a-form-item label="行业">
        <a-input v-model:value="selectedCompany.industry" />
      </a-form-item>
      <a-form-item label="Logo URL">
        <img :src="selectedCompany.logoUrl" alt="Logo" style="width: 50px; height: 50px; border-radius: 50%;" />
        <a-input v-model:value="selectedCompany.logoUrl" />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model:value="selectedCompany.description" />
      </a-form-item>
      <a-form-item label="网站">
        <a-input v-model:value="selectedCompany.website" />
      </a-form-item>
      <a-form-item label="地址">
        <a-input v-model:value="selectedCompany.address" />
      </a-form-item>
      <a-form-item label="创建者ID">
        <a-input v-model:value="selectedCompany.createdByUserId" />
      </a-form-item>
      <a-form-item label="是否认证">
        <a-switch v-model:checked="selectedCompany.isVerified" :checked-value="1" :un-checked-value="0" :checked-children="'已认证'" :un-checked-children="'未认证'" />
      </a-form-item>
      <a-form-item label="创建时间">
        <a-date-picker v-model:value="selectedCompany.createdAt" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 模态框 新增-->
  <a-modal v-model:open="open1" title="新增公司" :confirm-loading="confirmLoading1" @ok="handleOk1">
    <a-form ref="addForm" :model="addCompany" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
      <a-form-item label="公司名称" name="companyName">
        <a-input v-model:value="addCompany.companyName" />
      </a-form-item>
      <a-form-item label="行业">
        <a-input v-model:value="addCompany.industry" />
      </a-form-item>
      <a-form-item label="Logo URL">
        <img :src="addCompany.logoUrl" alt="Logo" style="width: 50px; height: 50px; border-radius: 50%;" />
        <a-input v-model:value="addCompany.logoUrl" />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model:value="addCompany.description" />
      </a-form-item>
      <a-form-item label="网站">
        <a-input v-model:value="addCompany.website" />
      </a-form-item>
      <a-form-item label="地址">
        <a-input v-model:value="addCompany.address" />
      </a-form-item>
      <a-form-item label="创建者ID" name="createdByUserId">
        <a-input v-model:value="addCompany.createdByUserId" />
      </a-form-item>
      <a-form-item label="是否认证">
        <a-switch v-model:checked="addCompany.isVerified" :checked-value="true" :un-checked-value="false" :checked-children="'已认证'" :un-checked-children="'未认证'" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs'; // 使用 dayjs 库来格式化日期
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
/* eslint-disable */

// 定义公司数据的类型
interface Company {
  companyId: number;
  companyName: string;
  industry: string;
  logoUrl: string;
  description: string;
  website: string;
  address: string;
  createdByUserId: number;
  isVerified: boolean;
  createdAt: string;
}

// 初始化 selectedCompany 为一个空的公司对象
const selectedCompany = ref<Company>({
  companyId: 0,
  companyName: '',
  industry: '',
  logoUrl: '',
  description: '',
  website: '',
  address: '',
  createdByUserId: 0,
  isVerified: false,
  createdAt: dayjs().toISOString(),
});

const addCompany = ref<AddCompany>({
  companyId: 0,
  companyName: '',
  industry: '',
  logoUrl: '',
  description: '',
  website: '',
  address: '',
  createdByUserId: undefined,
  isVerified: false,
  createdAt: dayjs().toISOString(),
});


// 定义表格结构
const columns = [
  {
    title: '公司名称',
    dataIndex: 'companyName',
  },
  {
    title: '行业',
    dataIndex: 'industry',
  },
  {
    title: 'Logo',
    dataIndex: 'logoUrl',
  },
  {
    title: '描述',
    dataIndex: 'description',
  },
  {
    title: '网站',
    dataIndex: 'website',
  },
  {
    title: '地址',
    dataIndex: 'address',
  },
  {
    title: '创建者ID',
    dataIndex: 'createdByUserId',
  },
  {
    title: '是否认证',
    dataIndex: 'isVerified',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
  },
  {
    title: '操作',
    dataIndex: 'action',
  }
];
interface AddCompany {
  companyId: number;
  companyName: string;
  industry: string;
  logoUrl: string;
  description: string;
  website: string;
  address: string;
  createdByUserId: number | undefined; // 注意创建者ID是必填项，但初始值可以是 undefined
  isVerified: boolean;
  createdAt: string;
}
// 表格数据
const companies = ref<Company[]>([]);
interface Pagination {
  current: number;
  pageSize: number;
  total?: number;
  [key: string]: any; // 可选字段，用于扩展其他属性
}
// 分页信息
const pagination = ref({
  pageSize: 10, // 设置每页显示10条数据
  total: 0,
  current: 1
});

// 数据加载状态
const isLoading = ref(true);

// 搜索关键字
const searchKeyword = ref<string>('');

// 是否搜索状态
const isSearch = ref(false);

// 日期格式化函数
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 表格分页逻辑
const handleTableChange = (pag: Pagination) => {
  console.log('handleTableChange', pagination);
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchCompanies();
  } else {
    handleSearch();
  }
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 获取公司列表
const fetchCompanies = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/companies/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;

    pagination.value.total = res.data.data.total;
    companies.value = res.data.data.list;
    console.log('Fetched companies:', companies.value);
    if (companies.value.length === 0 && pagination.value.current > 1) {
      pagination.value.current = pagination.value.current - 1;
      fetchCompanies();
    }
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

onMounted(async () => {
  await fetchCompanies();
  window.scrollTo({ top: 0, behavior: 'smooth' });
});

// 弹窗
const modalText = ref<string>('Content of the modal');
const open = ref<boolean>(false);
const open1 = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const confirmLoading1 = ref<boolean>(false);

// 显示修改弹窗
const showModal = (record: Company) => {
  if (record) {
    open.value = true;
    selectedCompany.value = {
      companyId: record.companyId,
      companyName: record.companyName,
      industry: record.industry,
      logoUrl: record.logoUrl,
      description: record.description,
      website: record.website,
      address: record.address,
      createdByUserId: record.createdByUserId,
      isVerified: record.isVerified,
      createdAt: dayjs(record.createdAt),
    };
    console.log('record:', record);
    modalText.value = JSON.stringify(record);
  } else {
    console.error('Invalid record passed to showModal:', record);
  }
};

// 删除确认
const deleteCompany = (record: Company) => {
  axios.post('/companies/delete', {
    companyId: record.companyId
  }).then(() => {
    if (!isSearch.value) {
      fetchCompanies();
    }
    if (companies.value.length === 0) {
      pagination.value.current = pagination.value.current - 1;
      handleSearch();
    }
    message.success('删除公司信息成功');
  }).catch(() => {
    message.error('删除公司失败，请稍后重试');
  });
};

// 修改确认
const handleOk = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 500);
  axios.post('/companies/update', {
    companyId: selectedCompany.value.companyId,
    companyName: selectedCompany.value.companyName,
    industry: selectedCompany.value.industry,
    logoUrl: selectedCompany.value.logoUrl,
    description: selectedCompany.value.description,
    website: selectedCompany.value.website,
    address: selectedCompany.value.address,
    createdByUserId: selectedCompany.value.createdByUserId,
    isVerified: selectedCompany.value.isVerified,
    createdAt: formatDate(selectedCompany.value.createdAt),
  }).then(res => {
    if (!isSearch.value) {
      fetchCompanies();
    } else {
      handleSearch();
    }
    console.log('更新公司信息成功:', res.data);
  }).catch(err => {
    console.error('更新公司失败:', err);
    alert('更新公司失败，请稍后重试');
  });
};

// 新增
const showModal1 = () => {
  open1.value = true;
};

// 新增确认
const addForm = ref<FormInstance | null>(null);
const handleOk1 = () => {
  addForm.value?.validateFields().then(() => {
    confirmLoading1.value = true;
    setTimeout(() => {
      open1.value = false;
      confirmLoading1.value = false;
    }, 500);
    axios.post('/companies/add', {
      companyName: addCompany.value.companyName,
      industry: addCompany.value.industry,
      logoUrl: addCompany.value.logoUrl,
      description: addCompany.value.description,
      website: addCompany.value.website,
      address: addCompany.value.address,
      createdByUserId: addCompany.value.createdByUserId,
      isVerified: addCompany.value.isVerified ? 1 : 0,
    }).then(res => {
      if (res.data.code === 200) {
        addCompany.value = {
          companyId: 0,
          companyName: '',
          industry: '',
          logoUrl: '',
          description: '',
          website: '',
          address: '',
          createdByUserId: undefined,
          isVerified: false,
          createdAt: dayjs().toISOString(),
        };
        if (!isSearch.value) {
          fetchCompanies();
        }
        message.success('添加公司成功');
      } else {
        message.error(res.data.message);
      }
    }).catch(() => {
      message.error('添加公司失败，请稍后重试');
    });
  }).catch((errorInfo) => {
    console.log('Failed:', errorInfo);
  });
};

// 搜索逻辑
const handleSearch = () => {
  axios.post('/companies/query', {
    companyName: searchKeyword.value,
  }).then(res => {
    isSearch.value = true;
    pagination.value.total = res.data.data.length;
    companies.value = res.data.data;
    isLoading.value = false;
  }).catch(err => {
    console.error('搜索失败:', err);
    isLoading.value = false;
  });
};

// 验证规则
const rules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
  ],
  createdByUserId: [
    { required: true, message: '请输入创建者ID', trigger: 'blur' },
  ],
};
</script>
